package com.wgzx.modbus.message;

import com.wgzx.modbus.entity.ModbusRsp;
import lombok.Data;

import java.io.Serializable;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Data
public class MsgHolder implements Serializable {

    private final int timeoutTimeMillis;
    private final int transactionIdentifier;
    private final Long createTimeMillis;
    private MsgListener<ModbusRsp> listener;
    private Future<?> timeoutFuture;

    public MsgHolder(int transactionIdentifier, int timeoutTimeMillis) {
        this.transactionIdentifier = transactionIdentifier;
        this.timeoutTimeMillis = timeoutTimeMillis;
        this.createTimeMillis = System.currentTimeMillis();
    }

    public void setTimeoutFuture(ScheduledExecutorService service, Runnable runnable) {
        this.timeoutFuture = service.schedule(runnable, timeoutTimeMillis, TimeUnit.MILLISECONDS);
    }

    public void cancelTimeoutFuture() {
        if(timeoutFuture != null) {
            try {
                timeoutFuture.cancel(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
